package com.rd.student.jike.class2.lihongming.week724_730.Day728.Serial;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Auther:Heinrich
 * @Date:2023/7/28-07-28-15:46
 * @Description:c230728
 * @version:1.0
 */
public class TestSerial {
    //基本数据类型可被序列化，自定义数据类型要实现Serializable接口保证可被序列化
    //如果没有实现会返回  NotSerializableException 异常
    public static void main(String[] args) throws Exception {
        Health health = new Health("健康");
        Person person = new Person("tom", 80,
                new Health("心脏病脑血栓"));
        Person zhangSan = new Person("张三",22,health);
        Person liSi = new Person("李四",19,health);
        Path path = Paths.get("object.txt");
        ObjectOutputStream oos = new ObjectOutputStream(
                Files.newOutputStream(path)
        );
        oos.writeObject(person);
        oos.writeObject(zhangSan);
        oos.writeObject(liSi);
        oos.writeObject(health);

        //同一个对象只会被序列化一次
        //序列化多次时，序列化和反序列化的顺序会一一对应

        //反序列化
        ObjectInputStream ois = new ObjectInputStream(
                Files.newInputStream(path)
        );
        System.out.println(ois.readObject());
        System.out.println(ois.readObject());
        System.out.println(ois.readObject());
        System.out.println(ois.readObject());

    }
}
